package com.ywm.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ywm.dto.QueryBlog;
import com.ywm.entity.Blog;
import com.ywm.service.BlogSrevice;
import com.ywm.service.ElasticSearchService;
import com.ywm.utils.Response;
import com.ywm.utils.ResponseResult;
import com.ywm.entity.PageBlog;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;


@RestController
public class BlogController {
    @Autowired
    BlogSrevice blogSrevice;
//    @Autowired
//    ElasticSearchService elasticSearchService;

    /*查询某个作者的博客*/
    @GetMapping(path = "/blogs/{page}/{size}/{username}")
    public ResponseResult<PageBlog> getBlogByPageAndAuthor(@PathVariable Integer page, @PathVariable Integer size, @PathVariable String username) {
        QueryBlog queryBlog = new QueryBlog();
        queryBlog.setAuthor(username);
        PageBlog blogByPage = blogSrevice.getBlogByPage(page, size, queryBlog);
        return Response.makeOKRsp(blogByPage);
    }

    //查询所有博客
    @GetMapping(path = "/blogs/{page}/{size}")
    public ResponseResult<PageBlog> getBlogByPage(@PathVariable Integer page, @PathVariable Integer size) {
        QueryBlog queryBlog = new QueryBlog();
        PageBlog blogByPage = blogSrevice.getBlogByPage(page, size, queryBlog);
        return Response.makeOKRsp(blogByPage);
    }

    @GetMapping(path = "/blogs")
    public ResponseResult<PageBlog> getBlogByPage() {
        /*QueryWrapper<PageBlog> wrapper = new QueryWrapper<>();*/
        PageBlog blogByPage = blogSrevice.getBlogByPage(1, 5, null);
        return Response.makeOKRsp(blogByPage);
    }

    /*分页带条件查询*/
    @PostMapping(path = "/blogs")
    public ResponseResult<PageBlog> getBlogByPage(@RequestBody QueryBlog queryBlog) {
        PageBlog blogByPage = blogSrevice.getBlogByPage(queryBlog.getCurrentPage(), queryBlog.getSize(), queryBlog);
        return Response.makeOKRsp(blogByPage);
    }

    /*明细查询*/
    @GetMapping(path = "/blog/{blogId}")
    public ResponseResult<Blog> getBlogByDetail(@PathVariable(name = "blogId") String blogId, boolean isEdit) {
        System.out.println("--------------------------------");
        System.out.println(isEdit);
        System.out.println("--------------------------------");
        QueryWrapper<Blog> wrapper = new QueryWrapper<Blog>();
        wrapper.eq("blog_id", blogId);
        Blog blog = blogSrevice.getOne(wrapper);
        if (!isEdit) {
            new Thread(() -> {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (blog.getBlogRead() == null) {
                    blog.setBlogRead(1);
                } else {
                    blog.setBlogRead(blog.getBlogRead() + 1);
                }
                blogSrevice.update(blog, wrapper);
            }).start();
        }
        return Response.makeOKRsp(blogSrevice.getOne(wrapper));
    }

    /**
     * @param blog 博客数据
     * @return 看看
     */
    @RequiresAuthentication
    @PutMapping(path = "/blog/edit")
    public ResponseResult<Blog> updateBlog(@RequestBody Blog blog) {
        //乐观锁
        Blog oldBlog = blogSrevice.getById(blog.getBlogId());
        blog.setVersion(oldBlog.getVersion());
        //返回时用
        blog.setIsDeleted(oldBlog.getIsDeleted());
        blog.setCreationDate(oldBlog.getCreationDate());
        boolean update = blogSrevice.updateById(blog);
        if (update) {
            return Response.makeOKRsp(blog);
        } else {
            return Response.makeErrRsp("更新失败，请重试");
        }
    }

    /**
     * 新增
     */
    @RequiresAuthentication
    @PostMapping(path = "/blog/save")
    public ResponseResult<Object> saveBlog(@RequestBody Blog blog) {
        System.out.println(blog);
        if (blog.getBlogId() == null || "".equals(blog.getBlogId())) {
//            elasticSearchService.saveOrUpdateToES(blog);
            blogSrevice.save(blog);
        } else {
            QueryWrapper<Blog> wrapper = new QueryWrapper<>();
            wrapper.eq("blog_id", blog.getBlogId());
//            elasticSearchService.updateEs(blog);
            blogSrevice.update(blog, wrapper);
        }
        return Response.makeOKRsp();
    }

    /*删除*/
    @RequiresAuthentication
    @DeleteMapping(path = "/blog/delete/{blogId}")
    public ResponseResult<Object> deleteBlog(@PathVariable String blogId) {
        boolean delete = blogSrevice.removeById(blogId);
//        ElasticSearchService.DeleteEs(blogId);
        if (delete) {
            return Response.makeOKRsp();
        } else {
            return Response.makeErrRsp("删除失败，请重试");
        }
    }

    /*分页带条件查询个人*/
    @RequiresAuthentication
    @PostMapping(path = "/myblogs")
    public ResponseResult<PageBlog> getBlogByPageAndAuthor(@RequestBody QueryBlog queryBlog) {
        PageBlog blogByPage = blogSrevice.getBlogByPageAndAuthor(queryBlog.getCurrentPage(), queryBlog.getSize(), queryBlog);
        return Response.makeOKRsp(blogByPage);
    }

    //根据类型分页查询
    /*分页查询*/
    @GetMapping(path = "/typeBlogs/{page}/{size}/{typeName}")
    public ResponseResult<PageBlog> getBlogByType(@PathVariable Integer page, @PathVariable Integer size, @PathVariable String typeName, String username) {
//        System.out.println("page: "+page+",size: "+size+", typeId: "+typeName+"username: "+username);
        Page<Blog> objectPage = new Page<>();
        objectPage.setCurrent(page);
        objectPage.setSize(size);
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<Blog>();
        queryWrapper.eq("blog_type", typeName);
//        queryWrapper.eq("author", username);
        Page<Blog> page1 = blogSrevice.page(objectPage, queryWrapper);
        PageBlog pageBlog = new PageBlog();
        pageBlog.setBlog(page1.getRecords());
        pageBlog.setCurrentPage(page1.getCurrent());
        pageBlog.setPageSize(page1.getPages());
        pageBlog.setSize(page1.getSize());
        pageBlog.setTotalSize(page1.getTotal());
        return Response.makeOKRsp(pageBlog);
    }

    //封面上传
    @PostMapping("uploadCover")
    public String uploadCover(MultipartFile file) {
        String s = blogSrevice.uploadFileAvatar(file);
        return s;
    }

    /**
     *
     * @param username 作者名
     * @return  返回该作者所写的博客
     */
    @GetMapping("user/blog/{username}")
    public List<Blog> getBlogByAuthor(@PathVariable String username){
        QueryWrapper<Blog> wrapper = new QueryWrapper<>();
        wrapper.eq("author",username);
        return blogSrevice.list(wrapper);
    }
}

